package com.maolong.controller.login;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.maolong.entity.domain.User;
import com.maolong.entity.format.Code;
import com.maolong.entity.format.RespResult;
import com.maolong.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@Slf4j
public class LoginController {

    @Autowired
    LoginService loginService;

    /**
     * 实现用户的登录操作
     * @param user
     * @return
     */
    @PostMapping("/login")
    public RespResult login(@RequestBody User user, HttpSession session){
        Integer code;
        log.info("前端登录信息{}",user);
        log.info("进行登录验证");
        //判断User的身份,根据身份返回不同的code
        System.out.println(user.getIdentify());
        if(user.getIdentify().getValue()==1){
            code= Code.SUCCESS_MANGER;
        }else if (user.getIdentify().getValue()==2){
            code= Code.SUCCESS_WORKER;
        }else
            code= Code.SUCCESS_USER;

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername()).eq("password",user.getPassword()).eq("identify",user.getIdentify());

        User user1 = loginService.getOne(queryWrapper);

        //打印查询结果
        System.out.println("查询结果"+user1);

        //根据查询结果返回不同的结果，前端根据状态码的不同，去跳转不同的页面
        if(user1!=null){
            System.out.println("登录成功");
            session.setAttribute("user",user1.getIdentify());
            return new RespResult(code,user1,"登录成功");
        }else
            return new RespResult(Code.FAIL,null,"账号或密码错误");
    }

    /**
     *
     * @param username
     * @return
     */
    @GetMapping("/login")
    public RespResult login(@RequestParam(value = "username",required = false) String username){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = loginService.getOne(queryWrapper);
        return new RespResult(Code.SUCCESS_PERSON,user.getId(),null);

    }
}
